/* 引入express框架 */
const express = require('express');
const app = express();
 
/* 引入cors */
const cors = require('cors');
app.use(cors());
 
/* 引入body-parser */
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
 
/* 引入mysql */

const mysql = require('mysql');
function reconnection(){
            conn = mysql.createConnection({   
            host: "localhost",
            user: "root",
            password: "",
            database:"webshopping"
           });
          conn.connect(function(err) {
           if(err){
               throw err;
               setTimeout('reconnection()', 1000);
           }
           });
          conn.on('error', function(err) {
                console.log(err);
                if(err.code === 'PROTOCOL_CONNECTION_LOST') {
                      reconnection();
                }
           });
    }
    reconnection();
 
/* 监听端口 */
app.listen(3000, () => {
    console.log('——————————服务已启动——————————');
})
 
app.get('/', (req, res) => {
    res.send('<p style="color:red">服务已启动</p>');
})

//滑动分类
app.get('/api/getslidercategory', (req, res) => {
    const sqlStr = 'SELECT * FROM category'
    conn.query(sqlStr, (error, results) => {
        if (error) return res.json({ status: 1, message: error})
        res.json({ status: 0, message: results})
    })

})

//宫格列表
app.get('/api/getgrid', (req, res) => {
    const sqlStr = 'SELECT * FROM grid'
    conn.query(sqlStr, (error, results) => {
        if (error) return res.json({ status: 1, message: error})
        res.json({ status: 0, message: results})
    })

})

//商品列表信息
app.get('/api/getgoodslist', (req, res) => {

    let category =req.query.category;//分类
  
    let limit=req.query.limit;//每页限制数量
    let pageindex=(req.query.pageindex)*limit;//页数
    console.log(category,pageindex,limit)
 
    const sqlStr = `SELECT * FROM goods_info 
    where category = '${category}'
    LIMIT ${pageindex},${limit}`
    console.log("Date:"+ new Date+"sql:"+sqlStr)

    conn.query(sqlStr, (error, results) => {
        if (error) return res.json({ status: 1, message: error})
        res.json({ status: 0, message: results})
    })

})

//首页轮播图
app.get('/api/getlunbo', (req, res) => {
    const sqlStr = 'SELECT * FROM carousel'
    conn.query(sqlStr, (error, results) => {
        if (error) return res.json({ status: 1, message: error})
        res.json({ status: 0, message: results})
    })

})

//商品轮播图
app.get('/api/goods/carousel/', (req, res) => {

    let id =req.query.id;//根据商品id获取该商品轮播图
    const sqlStr = `SELECT * FROM goods_carousel_img where id='${id}'`
    console.log(sqlStr)
    conn.query(sqlStr, (error, results) => {
        if (error) return res.json({ status: 1, message: error})
        res.json({ status: 0, message: results})
    })

})

//商品信息
app.get('/api/goods/info/', (req, res) => {

    let id =req.query.id;//根据商品id获取
    const sqlStr = `SELECT * FROM goods_info where id='${id}'`
    conn.query(sqlStr, (error, results) => {
        if (error) return res.json({ status: 1, message: error})
        res.json({ status: 0, message: results})
    })

})


//商品描述图
app.get('/api/goods/img', (req, res) => {

    let id =req.query.id;
    const sqlStr = `SELECT * FROM goods_info_img where id='${id}'`
    conn.query(sqlStr, (error, results) => {
        if (error) return res.json({ status: 1, message: error})
        res.json({ status: 0, message: results})
    })

})



//购物车商品信息
app.get('/api/goods/getshopcarlist', (req, res) => {

    let id =req.query.id;
    console.log(id)
    const sqlStr = `SELECT * FROM goods_info  where id in (${id})`
    conn.query(sqlStr, (error, results) => {
        if (error) return res.json({ status: 1, message: error})
        res.json({ status: 0, message: results})
    })

})


//全部商品
app.get('/api/goods/getallgoods', (req, res) => {

    const sqlStr = `SELECT * FROM goods_info `
    conn.query(sqlStr, (error, results) => {
        if (error) return res.json({ status: 1, message: error})
        res.json({ status: 0, message: results})
    })

})

//全部分类
app.get('/api/getallcategory', (req, res) => {
    const sqlStr = 'SELECT category FROM allcategory_info group by category ORDER BY  id asc'
    conn.query(sqlStr, (error, results) => {
        if (error) return res.json({ status: 1, message: error})
        res.json({ status: 0, message: results})
    })

})

//全部分类
app.get('/api/getallcategoryinfo', (req, res) => {
    const sqlStr = 'SELECT * FROM allcategory_info'
    conn.query(sqlStr, (error, results) => {
        if (error) return res.json({ status: 1, message: error})
        res.json({ status: 0, message: results})
    })

})





//全部商品
app.get('/api/getproducts', (req, res) => {
    
    let category =req.query.category;//分类
    let limit=req.query.limit;//每页限制数量
    let pageindex=(req.query.pageindex)*limit;//从哪个下标开始取
    console.log(category)
    if(category==="all"){
        var sqlStr = `SELECT * FROM goods_info 
    LIMIT ${pageindex},${limit}`
    }else{
        var sqlStr = `SELECT * FROM goods_info 
        where category = '${category}'
        LIMIT ${pageindex},${limit}`
    }

    console.log("Date:"+ new Date+"sql:"+sqlStr)

    conn.query(sqlStr, (error, results) => {
        if (error) return res.json({ status: 1, message: error})
        res.json({ status: 0, message: results})
    })

})

//微信登录
app.post('/wxlogin', (req, res) => {
	let data = req.body;
	console.log(req);		
    const sqlStr=`SELECT openid from user WHERE openid='${data.openId}'`
    //查询此id是否存在
    conn.query(sqlStr, (error, results) => {
        if (error) return res.json({ status: 1, message: error})
        //如果不存在将此id插入数据库
        if(results.length==0){
            const sqlStr=`INSERT INTO user(openid,nickname,gender,city,province,country,avatarurl,unionid) 
            VALUES('${data.openId}','${data.nickName}','${data.gender}','${data.city}','${data.province}','${data.country}','${data.avatarUrl}','${data.unionId}')`
            conn.query(sqlStr, (error, results) => {
                if (error) return res.json({ status: 1, message: error})
                // res.json(data)
            })
        }
        res.json(data)
    })

})
//添加地址

app.post('/addres', (req, res) => {
	let data = req.body;
	console.log(data);		
    const sqlStr=`INSERT INTO user_addres values('${data.openid}','${data.name}','${data.number}','${data.area}','${data.addres}','${data.checked}')`
    conn.query(sqlStr, (error, results) => {
        if (error) return res.json({ status: 1, message: error})
        res.json({ status: 0, message: results})
    })
})


Date.prototype.Format = function (fmt) { 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

//提交订单

app.post('/submitOrder', (req, res) => {
    let date = new Date().Format("yyyy-MM-dd hh:mm:ss");
    let data = req.body;
    let cart={};
    data.cart.forEach(item => {
    
      
    });
    
    console.log(JSON.stringify(data.cart))

    const sqlStr=`INSERT INTO \`order\`(openid,addresinfo,cart,status,amount,way,date) 
    values('${data.addresinfo.openid}','${JSON.stringify(data.addresinfo)}','${JSON.stringify(data.cart)}','已付款','${data.amount}','${data.way}','${date}')`
    console.log(sqlStr)
    conn.query(sqlStr, (error, results) => {
        if (error) return res.json({ status: 1, message: error})
        res.json({ status: 0, message: results})
    })
})

//获取我的订单

app.get('/api/myOrder', (req, res) => {
    console.log(req.query.openid)
    const sqlStr = `SELECT * FROM \`order\` WHERE openid='${req.query.openid}'`
    console.log(sqlStr)
    conn.query(sqlStr, (error, results) => {
        if (error) return res.json({ status: 1, message: error})
        res.json({ status: 0, message: results})
    })

})

//搜索关键字
app.get('/api/getSearchKey', (req, res) => {
  
    const sqlStr = `SELECT * FROM goods_info WHERE \`name\` LIKE '%${req.query.key}%'`
    console.log(sqlStr)
    conn.query(sqlStr, (error, results) => {
        if (error) return res.json({ status: 1, message: error})
        res.json({ status: 0, message: results})
    })

})

//搜索商品
app.get('/api/getSearchGoods', (req, res) => {
  
    const sqlStr = `SELECT * FROM goods_info WHERE \`name\` LIKE '%${req.query.key}%'`
    console.log(sqlStr)
    conn.query(sqlStr, (error, results) => {
        if (error) return res.json({ status: 1, message: error})
        res.json({ status: 0, message: results})
    })

})